package dev.hitools.svg2vector;

import com.android.ide.common.vectordrawable.Svg2Vector;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;

import static java.nio.file.FileVisitResult.CONTINUE;
import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;

public class Svg2VectorProcessor {
    private final Path svgPath;
    private final Path vectorPath;
    private final String extension;

    public Svg2VectorProcessor(String svgPath) {
        this(svgPath, "vector");
    }

    public Svg2VectorProcessor(String svgDir, String vectorPath) {
        this(svgDir, vectorPath, "xml");
    }

    public Svg2VectorProcessor(String svgDir, String vectorPath, String extension) {
        this.svgPath = Paths.get(svgDir);
        this.vectorPath = Paths.get(svgDir, vectorPath);
        this.extension = extension;
    }

    public void process() {
        if (!Files.isDirectory(svgPath)) {
            System.out.println("source not a directory");
            return;
        }
        try {
            EnumSet<FileVisitOption> options = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
            Files.walkFileTree(svgPath, options, Integer.MAX_VALUE, new FileVisitor<>() {
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
                    // Skip folder which is processing svgs to xml
                    if (dir.equals(vectorPath)) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }

                    CopyOption[] opt = new CopyOption[]{COPY_ATTRIBUTES, REPLACE_EXISTING};
                    Path newPath = vectorPath.resolve(svgPath.relativize(dir));
                    try {
                        Files.copy(dir, newPath, opt);
                    } catch (FileAlreadyExistsException ex) {
                        System.out.println("FileAlreadyExistsException " + ex.toString());
                    } catch (IOException x) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }
                    return CONTINUE;
                }

                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    convertToVector(file, vectorPath.resolve(svgPath.relativize(file)));
                    return CONTINUE;
                }

                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    return FileVisitResult.CONTINUE;
                }

                public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                    return CONTINUE;
                }
            });
        } catch (IOException e) {
            System.out.println("IOException " + e.getMessage());
        }
    }

    private void convertToVector(Path source, Path target) throws IOException {
        if (source.getFileName().toString().endsWith(".svg")) {
            File targetFile = getFileWithXMlExtension(target, extension);
            FileOutputStream fous = new FileOutputStream(targetFile);
            Svg2Vector.parseSvgToXml(source.toFile(), fous);
        } else {
            System.out.println("Skipping file as its not svg " + source.getFileName().toString());
        }
    }

    private File getFileWithXMlExtension(Path target, String extension) {
        String svgFilePath = target.toFile().getAbsolutePath();
        StringBuilder svgBaseFile = new StringBuilder();
        int index = svgFilePath.lastIndexOf(".");
        if (index != -1) {
            String subStr = svgFilePath.substring(0, index);
            svgBaseFile.append(subStr);
        }
        svgBaseFile.append(".");
        svgBaseFile.append(extension);
        return new File(svgBaseFile.toString());
    }

}
